package com.jswl.training.springjpa.controller;

import com.jswl.training.springjpa.common.state.Result;
import org.springframework.web.bind.annotation.*;
import org.springframework.web.multipart.MultipartFile;

import java.io.File;
import java.io.IOException;

@RestController
@RequestMapping("/upload")
public class UploadFileController {

    @PostMapping("/uploadFile")
    public Result uploadFile(@RequestParam("userId") String userId,@RequestPart("file") MultipartFile file) {
        if(file.isEmpty()){
            throw new RuntimeException("请选择上传文件!");
        }
        File dir = new File("upload");
        if(!dir.exists()){
            dir.mkdirs();
        }
        try {
            file.transferTo(new File(dir.getAbsolutePath()+File.separator+file.getOriginalFilename()));
        } catch (IOException e) {
            throw new RuntimeException("文件上传失败!");
        }
        return Result.ok(file.getOriginalFilename());
    }

}
